<template>
  <div class="create-project">
    <div class="page-header">
      <h1>创建项目</h1>
      <p>填写项目基本信息，开始您的项目管理之旅</p>
    </div>

    <el-card class="project-form-card">
      <el-form
        ref="formRef"
        :model="projectForm"
        :rules="formRules"
        label-width="120px"
        size="large"
      >
        <el-form-item label="项目名称" prop="name">
          <el-input
            v-model="projectForm.name"
            placeholder="请输入项目名称"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="项目描述" prop="description">
          <el-input
            v-model="projectForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入项目描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="项目状态" prop="status">
          <el-select v-model="projectForm.status" placeholder="请选择项目状态">
            <el-option label="规划中" value="PLANNING" />
            <el-option label="进行中" value="IN_PROGRESS" />
            <el-option label="已暂停" value="PAUSED" />
            <el-option label="已完成" value="COMPLETED" />
          </el-select>
        </el-form-item>

        <el-form-item label="优先级" prop="priority">
          <el-select v-model="projectForm.priority" placeholder="请选择优先级">
            <el-option label="低" value="LOW" />
            <el-option label="中" value="MEDIUM" />
            <el-option label="高" value="HIGH" />
            <el-option label="紧急" value="URGENT" />
          </el-select>
        </el-form-item>

        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker
            v-model="projectForm.startDate"
            type="date"
            placeholder="请选择开始日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker
            v-model="projectForm.endDate"
            type="date"
            placeholder="请选择结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="项目经理" prop="managerId">
          <el-select
            v-model="projectForm.managerId"
            placeholder="请选择项目经理"
            filterable
            remote
            :remote-method="searchUsers"
            :loading="userLoading"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.id"
              :label="user.realName || user.username"
              :value="user.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            创建项目
          </el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
// import { projectApi } from '@/api/project'
// import { userApi } from '@/api/user'
import type { User } from '@/types'

const router = useRouter()
const formRef = ref<FormInstance>()
const submitLoading = ref(false)
const userLoading = ref(false)
const userOptions = ref<User[]>([])

// 表单数据
const projectForm = reactive({
  name: '',
  description: '',
  status: 'PLANNING',
  priority: 'MEDIUM',
  startDate: '',
  endDate: '',
  managerId: null as number | null
})

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
    { min: 2, max: 100, message: '项目名称长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入项目描述', trigger: 'blur' },
    { max: 500, message: '项目描述不能超过 500 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择项目状态', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ],
  startDate: [
    { required: true, message: '请选择开始日期', trigger: 'change' }
  ],
  endDate: [
    { required: true, message: '请选择结束日期', trigger: 'change' }
  ],
  managerId: [
    { required: true, message: '请选择项目经理', trigger: 'change' }
  ]
}

// 模拟用户数据
const mockUsers: User[] = [
  { id: 1, username: 'zhangsan', realName: '张三', email: 'zhangsan@example.com', department: '技术部', role: 'DEVELOPER', avatar: '', status: 'ACTIVE', lastLoginAt: new Date(), createdAt: new Date(), loginCount: 10 },
  { id: 2, username: 'lisi', realName: '李四', email: 'lisi@example.com', department: '产品部', role: 'MANAGER', avatar: '', status: 'ACTIVE', lastLoginAt: new Date(), createdAt: new Date(), loginCount: 25 },
  { id: 3, username: 'wangwu', realName: '王五', email: 'wangwu@example.com', department: '设计部', role: 'DESIGNER', avatar: '', status: 'ACTIVE', lastLoginAt: new Date(), createdAt: new Date(), loginCount: 15 },
  { id: 4, username: 'zhaoliu', realName: '赵六', email: 'zhaoliu@example.com', department: '技术部', role: 'DEVELOPER', avatar: '', status: 'ACTIVE', lastLoginAt: new Date(), createdAt: new Date(), loginCount: 8 },
  { id: 5, username: 'sunqi', realName: '孙七', email: 'sunqi@example.com', department: '测试部', role: 'TESTER', avatar: '', status: 'ACTIVE', lastLoginAt: new Date(), createdAt: new Date(), loginCount: 12 },
  { id: 6, username: 'zhouba', realName: '周八', email: 'zhouba@example.com', department: '运营部', role: 'OPERATOR', avatar: '', status: 'ACTIVE', lastLoginAt: new Date(), createdAt: new Date(), loginCount: 20 }
]

// 加载所有用户
const loadAllUsers = async () => {
  try {
    userLoading.value = true
    // const response = await userApi.getAllUsers()
    // 模拟加载用户
    await new Promise(resolve => setTimeout(resolve, 500)) // 模拟网络延迟
    userOptions.value = mockUsers
  } catch (error) {
    console.error('加载用户失败:', error)
    ElMessage.error('加载用户列表失败')
  } finally {
    userLoading.value = false
  }
}

// 搜索用户
const searchUsers = async (query: string) => {
  if (!query) {
    userOptions.value = mockUsers
    return
  }
  
  try {
    userLoading.value = true
    // const response = await userApi.searchUsers({ keyword: query, page: 1, size: 10 })
    // 模拟搜索用户
    await new Promise(resolve => setTimeout(resolve, 300)) // 模拟网络延迟
    const filteredUsers = mockUsers.filter(user => 
      user.username.toLowerCase().includes(query.toLowerCase()) ||
      (user.realName && user.realName.includes(query))
    )
    userOptions.value = filteredUsers
  } catch (error) {
    console.error('搜索用户失败:', error)
  } finally {
    userLoading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    const valid = await formRef.value.validate()
    if (!valid) return
    
    // 验证日期
    if (projectForm.startDate && projectForm.endDate) {
      if (new Date(projectForm.startDate) >= new Date(projectForm.endDate)) {
        ElMessage.error('结束日期必须晚于开始日期')
        return
      }
    }
    
    submitLoading.value = true
    // await projectApi.createProject(projectForm)
    // 模拟创建项目
    
    ElMessage.success('项目创建成功')
    router.push('/projects')
  } catch (error) {
    console.error('创建项目失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 取消操作
const handleCancel = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要取消创建项目吗？已填写的信息将会丢失。',
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '继续编辑',
        type: 'warning'
      }
    )
    router.push('/projects')
  } catch {
    // 用户取消操作
  }
}

// 初始化
onMounted(() => {
  // 加载用户列表
  loadAllUsers()
})
</script>

<style scoped>
.create-project {
  padding: 24px;
  max-width: 800px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 24px;
  text-align: center;
}

.page-header h1 {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 8px;
}

.page-header p {
  font-size: 14px;
  color: #909399;
  margin: 0;
}

.project-form-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.el-form {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 24px;
}

.el-input,
.el-select,
.el-date-picker {
  width: 100%;
}

.el-textarea {
  width: 100%;
}

.el-button {
  margin-right: 12px;
}
</style>